﻿using System;
using System.Windows;
using Coevery.ViewModel.EntityDataService;
using Microsoft.Phone.Controls;
using System.Windows.Navigation;
using Coevery.ViewModel;
using Microsoft.Phone.Shell;
using System.Windows.Controls.Primitives;

namespace Coevery.PhoneApp
{
    public partial class OpportunityDetail : PhoneApplicationPage
    {
        private string _opportunityId;
        private Popup _popup;
        private OpportunityViewModel _opportunityViewModel;

        public OpportunityDetail()
        {
            InitializeComponent();
            _opportunityViewModel = new OpportunityViewModel();
            _opportunityViewModel.EnableButton += SetApplicationBarIconButtonEnabled;
            _opportunityViewModel.Popup = _popup = new Popup { Child = new PopuWait() };
            DataContext = _opportunityViewModel;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (e.NavigationMode != NavigationMode.Back)
            {
                _opportunityId = string.Empty;
                if (NavigationContext.QueryString.TryGetValue("Opportunity", out _opportunityId))
                {
                    _opportunityViewModel.OpportunityId = new Guid(_opportunityId);
                    _opportunityViewModel.LoadData();
                }
            }
        }

        private void AddComments_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Comment.xaml?Action=Add&ObjectType=Opportunity&ObjectId=" + _opportunityId, UriKind.Relative));
        }

        private void EditComment_Click(object sender, RoutedEventArgs e)
        {
            var menuItem = (MenuItem)sender;
            var note = (Note)menuItem.DataContext;
            PhoneApplicationService.Current.State["Note"] = note;

            NavigationService.Navigate(
                new Uri("/Comment.xaml?Action=Edit&ObjectType=Opportunity&ObjectId=" + _opportunityId, UriKind.Relative));
        }

        private void DeleteComment_Click(object sender, RoutedEventArgs e)
        {
            var menuItem = (MenuItem)sender;
            var note = (Note)menuItem.DataContext;
            note.IsDeleted = true;
            BaseViewModel.Context.UpdateObject(note);
            BaseViewModel.Context.BeginSaveChanges(OnNodeDeleted, BaseViewModel.Context);
        }

        private void OnNodeDeleted(IAsyncResult result)
        {
            Dispatcher.BeginInvoke(() => {
                _popup.IsOpen = true;
                SetApplicationBarIconButtonEnabled(false, null);
                BaseViewModel.Context.EndSaveChanges(result);
                _opportunityViewModel.LoadData();
            });
        }

        private void Refresh_Click  (object sender, EventArgs e)
        {
            var selectedPivotItem = ctlPanorama.SelectedItem as PivotItem;
            if (selectedPivotItem.Name == "PanDetail")
            {
                _opportunityViewModel.LoadData();
            }

            if (selectedPivotItem.Name == "PanComments")
            {
                _opportunityViewModel.LoadData();
            }
        }

        public void SetApplicationBarIconButtonEnabled(object sender, EventArgs e)
        {
            foreach (ApplicationBarIconButton item in ApplicationBar.Buttons)
            {
                item.IsEnabled = ((bool?)sender) ?? false;
            }
        }

        private void Home_Click(object sender, EventArgs e)
        {
            this.NavigationService.GoBack();
        }

        private void ApplicationBarMenuItem_Click(object sender, EventArgs e)
        {
            var statusCode = 1;
            var status = "in process";
            var menuItem = sender as ApplicationBarMenuItem;

            switch (menuItem.Text)
            {
                case "Convert to in process":
                    statusCode = 1;
                    status = "in process";
                    break;
                case "Convert to won":
                    statusCode = 3;
                    status = "won";
                    break;
                case "Convert to lost":
                    statusCode = 4;
                    status = "lost";
                    break;
            }

            var result = MessageBox.Show("Are you sure you want to convert the status to " + status + "?", "Information", MessageBoxButton.OKCancel);
            if (result == MessageBoxResult.OK)
            {
                var currentOpportunity = _opportunityViewModel.Opportunities[0];
                currentOpportunity.StatusCode = statusCode;
                BaseViewModel.Context.UpdateObject(currentOpportunity);
                BaseViewModel.Context.BeginSaveChanges(OnChangesSaved, BaseViewModel.Context);
            }
        }

        private void OnChangesSaved(IAsyncResult result)
        {
            Dispatcher.BeginInvoke(() => BaseViewModel.Context.EndSaveChanges(result));
        }

        private void PhoneApplicationPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (_popup.IsOpen == true)
            {
                _popup.IsOpen = false;
            }
        }
    }
}